package com.example.book.dao.impl;

import com.example.book.dao.BookDao;
import com.example.book.model.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
public class BookDaoImpl implements BookDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public int insert(Book book) {
        String sql = "insert into book(name,author,publisher,price,status) values (?,?,?,?,?)";
        return jdbcTemplate.update(sql,book.getName(),book.getAuthor(),book.getPublisher(),book.getPrice(),book.getStatus());

    }

    @Override
    public int delete(String id) {
        String sql = "delete from book where id = ?";
        return jdbcTemplate.update(sql,id);

    }

    @Override
    public int update(Book book) {
        String sql = "update book set name = ?, author = ?,publisher = ?,price = ?,status = ? where id = ?";
        return jdbcTemplate.update(sql,book.getName(),book.getAuthor(),book.getPublisher(),book.getPrice(),book.getStatus(),book.getId());
    }

    @Override

    public Book queryById(String id) {
        String sql = "select id, name, author, publisher, price, status from book where id = ?";

        return jdbcTemplate.queryForObject(sql,
                (rowSet, rowNum) -> {
                    Book book = new Book();
                    book.setId(rowSet.getInt("id"));
                    book.setName(rowSet.getString("name"));
                    book.setPublisher(rowSet.getString("publisher"));
                    book.setAuthor(rowSet.getString("author"));
                    book.setPrice(rowSet.getDouble("price"));
                    book.setStatus(rowSet.getInt("status"));
                    return book;
                },
                id);
    }

    @Override
    public Integer updateBookStatus(String bookId, String status) {
        String sql = "update book set status = ? where id = ?";
        return jdbcTemplate.update(sql,status,bookId);
    }
}
